/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

测试url  ：192.168.3.44:8080

*/
let token = uni.getStorage({
	key: 'token',
	success: function(res) {
		console.log(res.data);
	}
});
import signMd5Utils from '@/utils/sginMd5Utils.js';
export default {
	getToken() {
		let res
		try {
			const value = uni.getStorageSync('token');
			if (value) {
				res = value
			}
		} catch (e) {
			// error
			res = false
		}

		return res
	},
	config: {
		// baseUrl: "http://10.40.92.77:9561/",
		// baseUrl: "http://192.168.3.9:9551/",
		// baseUrl: 'http://39.105.196.2:9551/',
		// baseUrl: 'https://app.cardplaytest.com/',
		baseUrl: 'https://app.cardplayd.com/',
		// 192.168.60.77
		header: {
			'Content-Type': 'application/json;',
			// isEncrypt: false
			// 'Content-Type': 'application/x-www-form-urlencoded',
		},
		data: {},
		method: "GET",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},

	request(options) {
		const url = signMd5Utils.returnNewUrl(options.url)
		if (!options) {
			options = {}
		}
		uni.showLoading({
			title: '加载中',
			mask: true,
			success: (res) => {
				console.log(89)
			}
		})
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		//TODO 加密数据

		//TODO 数据签名
		const nonce =
			Math.random().toString(36).slice(-10) +
			Math.random().toString(36).slice(-10);
		// 生成当前的时间戳
		const timestamp = Number(new Date().getTime());
		const salt = "1s2JTL0F9u8^=m6-dW]6yLU1T50ppr8m";
		/* 
		_token = {'token': getStorage(STOREKEY_LOGIN).token || 'undefined'},
		_sign = {'sign': sign(JSON.stringify(options.data))}
		options.header = Object.assign({}, options.header, _token,_sign) 
		*/
		// let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJhcHBMb2dpbiIsImxvZ2luSWQiOiJhcHBfdXNlcjoxODgyMzgzMDg3OTU0ODI1MjE4Iiwicm5TdHIiOiJVTGdoYjZmbnFBb1hLVk9lZlNGZUlaTk1pcEs5dk50NyIsImNsaWVudGlkIjoiNDI4YTgzMTBjZDQ0Mjc1N2FlNjk5ZGY1ZDg5NGYwNTEiLCJ1c2VySWQiOjE4ODIzODMwODc5NTQ4MjUyMTgsImludml0ZUNvZGUiOiI4NjM2OTIiLCJwaG9uZSI6IjE1NjIxMzAwMzg3In0.S7zjxGlNY5p2GjucglVYfxEHWgYS1femQK7ACQmLdNM'//this.getToken()
		// console.log(token,'97');
		return new Promise((resolve, reject) => {
			let _config = null

			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				// console.log(this.interceptor.response);
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					// console.log(newResponse);
					if (newResponse) {
						response = newResponse
					}
				}
				// 统一的响应日志记录
				_reslog(response, options.url)
				if (statusCode === 200) { //成功
					uni.hideLoading()
					resolve(response.data);
				} else {
					uni.hideLoading()
					reject(response)
				}
			}

			// console.log(token,this.config,'111111111');
			if (token) {
				this.config.header.Authorization = "Bearer " + token
				// this.config.header.Cookie = "App-Token=" + token
				// console.log(token,this.config,'222222222');
			}
			/**
			 * 添加header签名
			 */
			this.config.header["Content-Language"] = "zh_CN";
			this.config.header["nonce"] = nonce;
			this.config.header["timestamp"] = timestamp;
			let sginStr
			sginStr = {
				timestamp: String(timestamp),
				nonce: nonce,
				salt: salt,
				url: url,
			}
			this.config.header["signature"] = signMd5Utils.getSign(
				sginStr
			);
			// 签名结束

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}

			// 统一的请求日志记录
			_reqlog(_config)

			if (process.env.NODE_ENV === 'development') {
				// console.log("【" + _config.requestId + "】 地址：" + _config.url)
				if (_config.data) {
					// console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
				}
			}

			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}

// function _filterUrl(url) {
// 	let flag
// 	if (url.indexOf('app/appsystem/user/queryAppUserInfo') !== -1 || url.indexOf('app/appsystem/user/knapsack') !== -1|| url.indexOf('app/appsystem/pay/queryPayStatus') !== -1) {
// 		flag = true
// 	} else {
// 		flag = false
// 	}
// 	return flag
// }

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	uni.hideLoading()
	return false;
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + req.requestId + "】 地址：" + req.url)
		if (req.data) {
			// console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res, url) {
	uni.hideLoading()
	console.log(res)
	console.log('================')
	console.log(url)
	let _statusCode = res.data.code;
	// console.log('_statusCode', _statusCode);
	switch (_statusCode) {

		case 200:
			break;
		case 401:
			uni.clearStorageSync()
			uni.redirectTo({
				url: '/pages/login/login',
			})
			break;
		case 403:
			uni.clearStorageSync()
			uni.redirectTo({
				url: '/pages/login/login',
			})
			break;
		case 404:
			break;
		default:
			break;
	}
	return false;
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + res.config.requestId + "】 地址：" + res.config.url)
		if (res.config.data) {
			// console.log("【" + res.config.requestId + "】 请求参数：" + JSON.stringify(res.config.data))
		}
		// console.log("【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库

}